package com.guaoran.source.zookeeper.common;

import org.omg.PortableInterceptor.INACTIVE;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/14 14:14
 */
public class RpcTCPTransport {
    String serviceAddress;

    public RpcTCPTransport(String serviceAddress) {
        this.serviceAddress = serviceAddress;
    }

    /**
     * 创建一个网络请求
     * @return
     */
    private Socket newSocket(){
        Socket socket = null;
        try {
            String[] hostAndPort = serviceAddress.split(":");
            socket = new Socket(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
            return socket;
        } catch (Exception e) {
            throw new RuntimeException("创建网络传输失败:"+e);
        }
    }

    /**
     * 向服务发起请求
     * @param request
     * @return
     */
    public Object sendRequest(RpcRequest request){
        Socket socket = null;
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        try {
            socket = newSocket();
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);
            outputStream.flush();
            inputStream = new ObjectInputStream(socket.getInputStream());
            Object result =  inputStream.readObject();
            inputStream.close();
            outputStream.close();
            return result;
        } catch (Exception e) {
            throw new RuntimeException("发起服务端请求失败："+e);
        }
    }
}
